package es.ats.codington.festival.servlets;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import es.ats.codington.festival.domain.Visitor;
import es.ats.codington.festival.services.VisitorService;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect("jsp/admin.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession sesion = request.getSession(true);
		if (sesion == null)
		{
			RequestDispatcher requestDispatcher = request.getRequestDispatcher("/");
	        requestDispatcher.forward(request, response);
		}
		else{
		
		
			Visitor visitor = new Visitor();
			VisitorService vs = new VisitorService();
			try {

					String username = request.getParameter("username");
					String password = request.getParameter("password");
		
					visitor.setUserName(username);
					visitor.setPassword(password);
		
					//If the visitor not exits
					int r=vs.login(visitor);
				
					if(r == 0)
					{
						request.setAttribute("error", "Wrong username or password. Please, try it again.");
						RequestDispatcher requestDispatcher = request.getRequestDispatcher("jsp/error.jsp");
				        requestDispatcher.forward(request, response);
					}		
					//if the visitor exits
					else
					{
						visitor=vs.getVisitorById(r);
						sesion.setAttribute("username", visitor.getUserName());
						sesion.setAttribute("peopleid", visitor.getPeopleId());
						sesion.setAttribute("isadmin", visitor.getAdmin());
						sesion.setAttribute("name", visitor.getFirstName() + " " + visitor.getLastName());
						sesion.setAttribute("email", visitor.getEmail());
						
						if(visitor.getAdmin())
						{
							RequestDispatcher requestDispatcher = request.getRequestDispatcher("jsp/home.jsp");
					        requestDispatcher.forward(request, response);
						}
						else
						{
							RequestDispatcher requestDispatcher = request.getRequestDispatcher("jsp/home.jsp");
					        requestDispatcher.forward(request, response);
						}
					}
				}
				catch (Exception e) {
					request.setAttribute("error", "Something were wrong with your loggin. Please, try it again in a few minutes.");
					response.sendRedirect("jsp/error.jsp");
				}
			}
		}
}
